package cn.tnar.parkservice.controller.financia;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.model.dto.InvoiceDTO;
import cn.tnar.parkservice.model.request.InvoiceRequest;
import cn.tnar.parkservice.model.response.PageResponse;
import cn.tnar.parkservice.model.response.QueryInvoiceDetailResponse;
import cn.tnar.parkservice.service.BWInvoiceService;
import cn.tnar.parkservice.service.KesbApiService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: xinZhang
 * @Date: 2019/8/28
 * @Description:
 */
@Api(tags = "财务管理（张鑫）")
@RestController
@RequestMapping("service/finacial")
@Slf4j
public class FinancialManageController {

    @Autowired
    private KesbApiService kesbApiService;

    @Autowired
    private BWInvoiceService bwInvoiceService;


    @ApiOperation("停车流水")
    @PostMapping("/parkBill")
    public ResultJson parkBill(@RequestBody Map<String,Object> param){
        try {
            log.info("停车流水：C接口请求参数，param：======>"+param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.PARK_BILL, param);
            log.info("停车流水：C接口返回参数，response：======>"+list);
            Collections.sort(list,Comparator.comparing(map->map.get("occur_date"),Comparator.reverseOrder()));
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("停车流水C接口调用异常===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    @ApiOperation("可提现金额")
    @PostMapping("/canWithDraw")
    public ResultJson canWithDraw(@RequestBody Map<String,Object> param){
        try {
            log.info("可提现金额：C接口请求参数，param：======>"+param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.CAN_WIHTDRAW, param);
            log.info("可提现金额：C接口返回参数，response：======>"+list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("可提现金额C接口调用异常===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    @ApiOperation("查询月卡会员变更记录")
    @PostMapping("/membermountInfo")
    public ResultJson queryCarMembermountInfo(@RequestBody Map<String,Object> param){
        try {
            log.info("查询月卡会员变更记录：C接口请求参数，param：======>"+param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.PARK_CAR_MEMBERMOUUT, param);
            log.info("查询月卡会员变更记录：C接口返回参数，response：======>"+list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("查询月卡会员变更记录C接口调用异常===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    @ApiOperation("提现记录")
    @PostMapping("/withDraw")
    public ResultJson withDrawRecord(@RequestBody Map<String,Object> param){
        try {
            log.info("提现记录：C接口请求参数，param：======>"+param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.WITHDRAW_RECORD, param);
            log.info("提现记录：C接口返回参数，response：======>"+list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("提现记录C接口调用异常===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    @ApiOperation("查询清算账户资金变动记录")
    @PostMapping("/clearAccount")
    public ResultJson clearAccount(@RequestBody Map<String,Object> param){
        try {
            log.info("查询清算账户资金变动记录：C接口请求参数，param：======>"+param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.CLEAR_ACCOUNT_RECORD, param);
            log.info("查询清算账户资金变动记录：C接口返回参数，response：======>"+list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("清算账户资金变动记录C接口调用异常===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    /**
     * 分页批量查询发票(作废)
     *
     * @param invoiceRequest
     * @return
     */
    @PostMapping(value = "queryYun1")
    public ResultJson queryYun1(@RequestBody InvoiceRequest invoiceRequest){
        try {
            if ("00".equals(invoiceRequest.getInvoiceStatus())){
                invoiceRequest.setInvoiceStatus("3");
            }else if ("02".equals(invoiceRequest.getInvoiceStatus())){
                invoiceRequest.setInvoiceStatus("10");
            }else if ("03".equals(invoiceRequest.getInvoiceStatus())){
                invoiceRequest.setInvoiceStatus("5");
            }else{
                invoiceRequest.setInvoiceStatus("0");
            }
            if ("0".equals(invoiceRequest.getInvoiceType())){
                invoiceRequest.setInvoiceType("1");
            }else if ("1".equals(invoiceRequest.getInvoiceType())){
                invoiceRequest.setInvoiceType("2");
            }else{
                invoiceRequest.setInvoiceType("0");
            }
            QueryInvoiceDetailResponse response = bwInvoiceService.getQueryInvoiceV2(
                    invoiceRequest.getStartTime(),invoiceRequest.getEndTime(),Integer.parseInt(invoiceRequest.getInvoiceStatus()),
                    Integer.parseInt(invoiceRequest.getInvoiceType()), 0, invoiceRequest.getPark_code(), 100, 1);
            List<InvoiceDTO> respList = new ArrayList<>();

            for (int i = 0; i < response.getData().getList().size();i ++){
                InvoiceDTO info = new InvoiceDTO();
                info.setInvoiceType(response.getData().getList().get(i).get("has_red").toString());
                info.setInvoicePrice(response.getData().getList().get(i).get("ticket_total_amount_has_tax").toString());
                if ("3".equals(response.getData().getList().get(i).get("state").toString())){
                    info.setInvoiceStatus("00");
                }else if ("5".equals(response.getData().getList().get(i).get("state").toString())){
                    info.setInvoiceStatus("03");
                }else{
                    info.setInvoiceStatus("02");
                }
                info.setApplyDate(response.getData().getList().get(i).get("apply_time").toString());
                info.setInvoiceDate(response.getData().getList().get(i).get("create_at").toString());
                info.setSerialNo(response.getData().getList().get(i).get("order_no").toString());
                info.setBuyerName(response.getData().getList().get(i).get("buy_name").toString());
                info.setBuyerBankAccount(String.valueOf(response.getData().getList().get(i).get("buy_acct")));
                info.setBuyerPhone(String.valueOf(response.getData().getList().get(i).get("buy_tel")));
                info.setInvoiceCode("");
                info.setInvoiceNo("");
                info.setBuyerAddressTel("");
                info.setSellerAddressTel("");
                info.setBuyerTaxNo("");
                info.setGoodsName("停车费");
                respList.add(info);
            }
            PageResponse page = new PageResponse();
            Integer pageNo = invoiceRequest.getPageNo();
            Integer pageSize = invoiceRequest.getPageSize();
            //刚开始的页面为第一页
            if (page.getCurrent() == null){
                page.setCurrent(1);
            }else {
                page.setCurrent(invoiceRequest.getPageNo());
            }
            //设置每页数据条数
            page.setSize(pageSize);
            //设置每页开始记录数
            page.setStar((pageNo - 1) * pageSize);
            //获取数据集合大小 设置总记录数
            int size = respList.size();
            page.setTotal(Long.valueOf(String.valueOf(size)));
            //设置总页数
            page.setPages(size % pageSize == 0 ? size/pageSize : size/pageSize+1);
            //对结果集进行截取
            Integer start = page.getStar();
            Integer end = size - start > pageSize ? start + pageSize : size;
            if (start < end){
                //排序 按开票时间倒叙
                Collections.sort(respList, Comparator.comparing(InvoiceDTO :: getInvoiceDate, Comparator.nullsLast(String::compareTo)).reversed());
                page.setRecords(respList.subList(start,end));
            }

            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
        } catch (Exception e) {
            log.error("查询电子发票异常！", e);
        }
        return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
    }

}
